home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3884 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: Rezonet.net!news
  2. From: ray@ultimate-tech.com (Ray Dunn)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Recursive function -> how do you exit one?
  5. Date: 29 Jan 1996 01:26:06 GMT
  6. Organization: Ultimate Technographics Inc.
  7. Message-ID: <4eh7ne$166g@ns.RezoNet.NET>
  8. References: <4eh1g8$aba@pulp.ucs.ualberta.ca>
  9. NNTP-Posting-Host: 204.19.230.7
  10. Mime-Version: 1.0
  11. Content-Type: Text/Plain; charset=US-ASCII
  12. X-Newsreader: WinVN 0.99.7
  13.  
  14. In referenced article, Jacob Bukczynski says...
  15. >
  16. >I'm using a recursive function to search for files. I need
  17. >it to quit when a user presses Esc.
  18. >
  19. >Using 
  20. >
  21. >return;
  22. >
  23. >doesn't seem to work, the funtion runs again. ( I tested
  24. >this by putting a printf statement in front of the return -
  25. >it got printed over and over again. )
  26.  
  27. Each call of the function returns through its end or return call in the 
  28. normal way. So that in:
  29.  
  30.   void f(int n)
  31.   {
  32.     printf("IN %d ", n);
  33.  
  34.     if (n < 2) 
  35.       f(n+1);
  36.  
  37.     printf("OUT %d ", n);
  38.     return;
  39.   }
  40.  
  41. if f(0) is called, it would print
  42.  
  43.   IN 0 IN 1 IN 2 OUT 2 OUT 1 OUT 0
  44.  
  45. - IN's when the function recurses in, then OUT's as all calls of the 
  46. function return.
  47.  
  48. If you want to do something special to unwind the calls, on an error or 
  49. special user input say, then you either have to use a setjmp in the 
  50. function which makes the first call of the recursive function, and use 
  51. longjmp to get out, or, more normally, you must return an error code 
  52. which you test after the recursive call, to ensure that the calls 
  53. unwind immediately.
  54.  
  55.   int f(some_parameters)
  56.   { int ret;
  57.  
  58.     some_processing...
  59.  
  60.     if (some_error_condition)
  61.       return(-1);
  62.  
  63.     some_more_processing...
  64.  
  65.     ret = f(some_args);  /* recursive call */
  66.     if (ret == -1)
  67.       return(-1);    /* return immediately if error */
  68.  
  69.     some_other_processing...
  70.  
  71.     return(0);
  72.   }
  73. -- 
  74. Ray Dunn (opinions are my own) | Phone: (514) 938 9050
  75. Montreal                       | Phax : (514) 938 5225
  76. ray@ultimate-tech.com          | Home : (514) 630 3749
  77.  
  78.